<template>
  <div class="testedit-content">
    <el-form ref="form" :model="form" v-bind="getFormProps()">
      <el-table
        :data="editTableList"
        tooltip-effect="dark" 
        class="edit_table">
        <el-table-column 
          prop="testModeName"
          label="测试项"
          width="90"  
          align="center">
        </el-table-column>
        <el-table-column 
          prop="testMethodName"
          label="测试内容"
          align="center">
        </el-table-column>
        <el-table-column 
          prop="testResult"
          label="测试结果"
          align="center">
          <template slot-scope="scope">
            <!-- testScoreType 主观题-0 非主观-1 -->
            <el-form-item prop="editScore"
              label-width="0"
              :rules="rules">
              <el-row v-if="scope.row.testScoreType === TEST_SCORE_TYPE.OBJECT">
                <el-col :span="24" >
                  <el-input-number class="input-small" v-model="form.editScore" :max="999" :bit="0.01" no-zero placeholder="请输入测试结果">
                    <template slot="append">{{scope.row.unitName}}</template>
                  </el-input-number>
                </el-col>
              </el-row>
              <el-row v-else>
                <el-col :span="24">
                  <el-select v-model="form.editScore" value-key="id">
                    <el-option v-for="item in standardData.list" :key="item.id" :label="item.testGrade" :value="item"></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <!-- 防止呗表单验证影响美观 -->
            <el-row v-if="scope.row.testScoreType === TEST_SCORE_TYPE.OBJECT" style="margin-top: 10px;">
              <el-col :span="24">
                <el-button type="text" @click="showStandardDialog(scope.row, $event)">查看评分标准</el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column 
          v-if="isShowScoreDetail"
          prop="scoureDetaiList"
          label="额外加减分项"
          align="center"
          width="290">
          <template slot-scope="scope">
            <el-checkbox-group v-model="scope.row.editExtVal">
              <el-row v-for="item in scope.row.scoureDetaiList" :key="item.id">
                <el-col style="text-align: left;" :span="18">{{item.testDetail}}</el-col>
                <el-col :span="3">{{item.score + item.unit}}</el-col>
                <el-col class="check-item" :span="2">
                  <el-checkbox :label="item">{{item.score}}</el-checkbox>
                </el-col>
              </el-row>
            </el-checkbox-group>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="80"
          align="center">
          <template slot-scope="scope">
            <el-button @click="handleSave(scope.$index, scope.row)" type="link">确定</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="btn-wrapper">
      <el-button @click="goBack" type="default">返回</el-button>
    </div>
    <el-dialog
      class="standard-dialog"
      :title="standardData.scoreTitle"
      :visible="standardDialogShow"
      :before-close="handleDialogClose">
      <el-row :gutter="15">
        <el-col :span="10">
          <div class="title">{{standardData.scoreTitle}}</div>
          <el-table class="standart-table" :data="standardData.list" :show-header="false">
            <el-table-column prop="testGrade" align="center"></el-table-column>
            <el-table-column prop="symbol"  align="center">
              <template slot-scope="scope">
                <span v-if="!scope.row.minValue">{{scope.row.symbol}} {{scope.row.maxValue}}</span>
                <span v-else-if="!scope.row.maxValue">{{scope.row.symbol}} {{scope.row.minValue}}</span>
                <span v-else>{{scope.row.minValue}} {{scope.row.symbol}} {{scope.row.maxValue}}</span>
              </template>
            </el-table-column>
          </el-table>
          <div class="ext-data-wrapper">
            <p v-for="(item, index) in standardData.extData" :key="item.id">{{`${index + 1}. ${item.testDetail} ${item.score}${item.unit}`}}</p>
          </div>
        </el-col>
        <el-col :span="14" v-if="testStandardData">
          <div class="title">{{testStandardData.title}}</div>
          <div class="standard-content">
            <div class="text" v-html="testStandardData.content"></div>
            <img class="image" v-if="testStandardData.imageUrl" :src="testStandardData.imageUrl"/>
            <div class="text" v-html="testStandardData.other"></div>
          </div>
        </el-col>
      </el-row>
      <div class="btn-wrapper">
        <el-button type="primary" @click="handleDialogClose">确定</el-button>
      </div>
      </el-dialog>
  </div>
</template>

<script>
import filters from 'src/filters'
import {form} from 'utils/mixins'
import { mapGetters } from 'vuex'
import trainApi from 'api/train'
import standardItemData from './StandardData'
const TEST_SCORE_TYPE = {
  'SUBJECT': '0', // 主观
  'OBJECT': '1' // 非主观
}
export default {
  mixins: [form],
  props: {
    testDate: {
      type: String
    }
  },
  computed: {
    ...mapGetters({
      studentDetailInfo: 'train_student_detail'
    }),
    testModeId () {
      return this.$route.query.testModeId
    },
    testMethodId () {
      return this.$route.query.testMethodId
    },
    studentId () {
      return this.$route.query.studentId
    },
    testStandardData () {
      let UData = standardItemData[this.studentDetailInfo.testAgeName] || {}
      let data = UData[`data${this.testMethodId}`]
      return data
    }
  },
  data () {
    return {
      TEST_SCORE_TYPE,
      rules: [],
      standardDialogShow: false,
      isShowScoreDetail: false,
      form: {
        editScore: ''
      },
      standardData: {
        title: '',
        list: [],
        extData: []
      }, // 评分标准
      editTableList: [] // 具体项木录入
    }
  },
  mounted () {
    this.initData()
  },
  methods: {
    initData (testData, ageId) {
      // this.studentDetailInfo 不是空对象
      // if (this.studentDetailInfo && isNaN(this.studentDetailInfo.id - 0)) {
      //   setTimeout(() => {
      //     this.initData(testData, ageId)
      //   }, 200)
      // } else {
      //   this.getStuItemScoreRuleInfo(testData, ageId)
      // }
      this.getStuItemScoreRuleInfo(testData, ageId)
    },
    getStuItemScoreRuleInfo (testDate, ageId) {
      // 提供给父层调用 切换时间时
      ageId = ageId || this.studentDetailInfo.testAgeId // 默认传入  修改年龄组时需要
      testDate = testDate || this.testDate || filters.FormatDate(new Date().getTime(), 'yyyy-MM-dd')
      trainApi.getStuItemScoreRuleInfo({
        sportType: 3002,
        testDateStr: testDate,
        testModeId: this.testModeId,
        testMethodId: this.testMethodId,
        studentId: this.studentDetailInfo.id,
        ageDictionarieId: ageId
      }).then(({data}) => {
        data.testScoreType = data.testScoreType + '' // 转为字符串
        this.isShowScoreDetail = !!data.scoureDetaiList // 存在则显示额外加减分项
        data.editExtVal = data.scoureDetaiList ? data.scoureDetaiList.filter(k => k.flag) : [] // 额外加减分项
        this.editTableList = [data] || []
        // testScoreType 主观题-0-选择 非主观-1-输入
        let rules = []
        if (data.testScoreType === TEST_SCORE_TYPE.SUBJECT) {
          rules = [
            {required: true, message: '请选择测试结果'}
          ]
          this.getStuItemScoreStandardInfo().then((res) => {
            this.form.editScore = (res.data ? res.data.find(k => k.maxValue - 0 === data.testScore - 0) : '') || ''
          })
        } else {
          this.form.editScore = data.testScore || 0
          rules = [
            {required: true, message: '请输入测试结果'},
            {
              validator (rule, value, callback) {
                if (value >= 1) {
                  callback()
                } else {
                  callback(new Error('请输入测试结果且不能小于1'))
                }
              }
            }
          ]
        }
        this.rules = rules
      })
    },
    handleSave (index, row) { // 编辑
      this.validate(() => {
        let subData = {}
        // 额外加减分项
        subData.studentId = this.studentDetailInfo.id
        subData.testDate = this.testDate
        subData.testModeId = this.testModeId
        subData.testMethodId = this.testMethodId
        if (row.testScoreType === TEST_SCORE_TYPE.SUBJECT) {
          subData.testScore = this.form.editScore.maxValue // 主观 选择的分值 大小一样 随意选一个
        } else {
          subData.testScore = this.form.editScore // 非主观 输入
        }
        subData.testScoreDesc = row.unitName // 输入分值的单位
        subData.testScoreType = row.testScoreType // 主观题0 =  输入 非主观题2 = 选择
        subData.testLevelId = this.studentDetailInfo.testAgeId // 年龄组IDS
        subData.extraTestScores = row.editExtVal && !row.editExtVal.length ? undefined : row.editExtVal.map(item => {
          return {
            testMethodId: item.id,
            testScore: item.score - 0, // 转为数值型
            testScoreDesc: item.unit
          }
        })
        trainApi.saveStuTestScore(JSON.stringify(subData)).then((res) => {
          // 成功跳转回首页jieg
          this.goBack()
        })
      })
    },
    goBack () {
      this.$router.push({
        path: '/training/student/test',
        query: {
          studentId: this.studentId
        }
      })
    },
    showStandardDialog (row, event) {
      this.getStuItemScoreStandardInfo({context: event.target}).then(({data}) => {
        this.standardData.scoreTitle = row.testMethodName + '评分标准'
        this.standardData.extData = row.scoureDetaiList
        this.standardDialogShow = true
      })
    },
    getStuItemScoreStandardInfo (options = {}) {
      return new Promise((resolve) => {
        trainApi.getStuItemScoreStandardInfo({
          sportType: 3002,
          testDateStr: this.testDate,
          testModeId: this.testModeId,
          testMethodId: this.testMethodId,
          studentId: this.studentDetailInfo.studentId,
          ageDictionarieId: this.studentDetailInfo.testAgeId
        }, options).then(({data}) => {
          this.standardData.list = data || []
          resolve({data})
        })
      })
    },
    handleDialogClose () {
      this.standardDialogShow = false
    }
  }
}
</script>
<style lang="scss">
  .testedit-content{
    .edit_table{
      .el-table__body{
        .el-table__row{
          &:hover{
            >td{
              background-color: inherit;
            }
          }
          &:last-child{
            td{
              border-bottom: none;
            }
          }
          .cell {
            padding: 22px 8px;
            .el-form-item{
              margin-bottom: 0;
            }
            .el-form-item__error{
              right: 0;
              text-align: center;
            }
          }
          .el-input-number {
            width: auto;
            .el-input__inner{
              height: 34px;
            }
          }
        }
      }
      .el-checkbox-group{
        .check-item{
          .el-checkbox{
            width: 20px;
            left: 2px;
            top: -2px;
            min-width: auto;
            margin-right: 0;
            .el-checkbox__label{
              width: 0;
              visibility: hidden;
            }
          }
        }
      }
    }
    .standard-dialog{
      .el-dialog{
        width: 740px;
        .title{
          margin-bottom: 20px;
          font-size: 14px;
          text-align: center;
        }
        .standart-table{
          border-top: 1px solid #f2f2f2;
          border-left: 1px solid #f2f2f2;
          td{
            border-right: 1px solid #f2f2f2;
          }
        }
        .ext-data-wrapper{
          margin-top: 8px;
          line-height: 30px;
          color: $color-sub;
        }
        .standard-content{
          .text{
            margin-bottom: 8px;
            line-height: 22px;
          }
          .image{
            margin-bottom: 8px;
          }
        }
        .btn-wrapper{
          margin-top: 20px;
          text-align: center;
        }
      }
    }
    .btn-wrapper{
      margin-top: 35px;
      text-align: center;
    }
  }
  
</style>
